<template>
	<view class="">
		<view class="headerMain"></view>
		<view class="content">
			<!-- app端内实现获取Android手机系统所有的应用列表 -->
			<view class="testBtn" @click="getAllApply">测试</view>
		</view>

	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				isShow: true,
				dataArr: [],
			}
		},
		onLoad() {

		},
		onShow() {
			var platform = uni.getSystemInfoSync().platform;
			console.log("platform：",platform);
			this.initContacts();
		},
		methods: {
			// 初始化通讯录
			initContacts: function() {
				console.log("initContacts");
				// #ifdef APP-PLUS
				//获取手机通讯录
				plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => {
					// console.log("addressbook:",addressbook);
					addressbook.find(["displayName", "phoneNumbers"], (contacts) => {
						console.log("contacts:",contacts);
						let temp = [];
						contacts.forEach((item) => {
							// let FirstE = this._parseChar(item.displayName);
							// let FirstE = item.displayName;
							// let unicode = FirstE.charCodeAt();
							// let index = parseInt(unicode - 65);
							// console.log("index：",index);
							let text = item.displayName.slice(0, 1)
							// item.phoneNumbers.forEach(item_phone => {
							// 	// item_phone.value = this.GetMobile(item_phone.value);
							// 	// this.IsInvitedFun(item_phone.value);
							// 	let contact = {
							// 		// 'text': text,
							// 		'name': item.displayName,
							// 		'phone': item_phone.value,
							// 	}
							// 	console.log("contact：",contact);
							// 	console.log("this.dataArr[index].Arr：",this.dataArr[index].Arr);
							// 	temp = this.dataArr[index].Arr == undefined ? [] : this
							// 		.dataArr[index].Arr;
							// 	let string = JSON.stringify(temp);
							// 	console.log("string：",string);
							// 	if (string.indexOf(item_phone.value) == -1) {
							// 		temp.push(contact);
							// 	}
							// 	this.dataArr[index].Arr = temp;
							// });
							let data = {
								'text': text,
								'id': item.id,
								'name': item.displayName,
								'phone': item.phoneNumbers[0].value,
							}
							this.dataArr.push(data);
							// console.log("总数据：",this.dataArr.push(data));
						});
						console.log("dataArr：",this.dataArr);
						// this.contactItems = JSON.parse(JSON.stringify(this.dataArr))
						// console.log("contactItems：",this.contactItems);
					}, (e) => {
						this.onAddressBookSetting()
					});
				}, (e) => {
					this.onAddressBookSetting()
				});
				// #endif
			},
			// 权限设置
			onAddressBookSetting: function() {
				console.log("onAddressBookSetting");
				if (this.isShow) {
					return
				}
				this.isShow = true
				uni.showModal({
					title: '提示',
					content: 'APP通讯录权限没有开启，是否开启？',
					success(res) {
						if (res.confirm) {
							if (platform == 'ios') {
								var UIApplication = plus.ios.import("UIApplication");
								var NSURL2 = plus.ios.import("NSURL");
								var setting2 = NSURL2.URLWithString("app-settings:");
								var application2 = UIApplication.sharedApplication();
								application2.openURL(setting2);
								plus.ios.deleteObject(setting2);
								plus.ios.deleteObject(NSURL2);
								plus.ios.deleteObject(application2);
							} else {
								var main = plus.android.runtimeMainActivity();
								var bulid = plus.android.importClass("android.os.Build");
								var Intent = plus.android.importClass('android.content.Intent');
								if (bulid.VERSION.SDK_INT >= 9) {
									var intent = new Intent('android.settings.APPLICATION_DETAILS_SETTINGS');
									var Uri = plus.android.importClass('android.net.Uri');
									var uri = Uri.fromParts("package", main.getPackageName(), null)
									intent.setData(uri);
									intent.putExtra('android.content.Intent.setFlags', Intent
										.FLAG_ACTIVITY_NEW_TASK);
								} else if (bulid.VERSION.SDK_INT <= 8) {
									var intent = new Intent(Intent.ACTION_VIEW);
									intent.setClassName("com.android.settings",
										"com.android.settings.InstalledAppDetails");
									intent.putExtra("com.android.settings.ApplicationPkgName", main
									.getPackageName());
									intent.putExtra('android.content.Intent.setFlags', Intent
										.FLAG_ACTIVITY_NEW_TASK);
								}
								main.startActivity(intent);
								this.isShow = false
							}
						} else {
							uni.navigateBack({
								delta: 1
							})
						}
					}
				})
			},
			getAllApply() {
				console.log("进来了");
				// #ifdef APP-PLUS
				console.log("1111");
				console.log("plus.contacts.ADDRESSBOOK_PHONE:", plus.contacts.ADDRESSBOOK_PHONE);
				console.log("plus.contacts.ADDRESSBOOK_SIM:", plus.contacts.ADDRESSBOOK_SIM);
				const main = plus.android.runtimeMainActivity();
				console.log("main：", main);
				const pManager = plus.android.invoke(main, 'getPackageManager');
				const ApplicationInfo = plus.android.importClass("android.content.pm.ApplicationInfo");
				const packages = plus.android.invoke(pManager, 'getInstalledPackages', 0);
				const total = plus.android.invoke(packages, 'size');
				console.log("total：", total);
				let appInfoList = [];
				for (let i = 0; i < total; i++) {
					try {
						const packageInfo = plus.android.invoke(packages, 'get', i);
						// 获取包名  
						const packName = plus.android.getAttribute(packageInfo, 'packageName');
						const versionName = plus.android.getAttribute(packageInfo, 'versionName');
						const versionCode = plus.android.getAttribute(packageInfo, 'versionCode');
						// console.log("packName：",packName,"----versionName：",versionName,"---versionName：",versionName)
						const appInfo = plus.android.invoke(pManager, 'getApplicationInfo', packName, 0);
						const appName = plus.android.invoke(pManager, 'getApplicationLabel', appInfo);
						const appApkPath = appInfo.plusGetAttribute("sourceDir");
						// console.log("appApkPath：", appApkPath);
						// 获取图标
						const appIcon = plus.android.invoke(pManager, 'getApplicationIcon', appInfo);
						const appIconBitmap = plus.android.invoke(appIcon, "getBitmap"); // 从BitmapDrawable获取Bitmap
						// 获取当前app的files文件夹路径
						const dir = main.getExternalFilesDir(null);
						const appFilesPath = plus.android.invoke(dir, "getAbsolutePath");

						// 是否是系统软件
						const isSystem = packageInfo.plusGetAttribute("applicationInfo").plusGetAttribute('flags') &
							ApplicationInfo.FLAG_SYSTEM != 0 ? true : false;
						// console.log("isSystem：",isSystem);
						// 判断是否是系统文件
						if (!isSystem) {

							// 转换成 Byte 然后写入文件
							const Bitmap = plus.android.importClass("android.graphics.Bitmap");
							const ByteArrayOutputStream = plus.android.newObject("java.io.ByteArrayOutputStream");
							plus.android.invoke(appIconBitmap, "compress", Bitmap.CompressFormat.PNG, 50,
								ByteArrayOutputStream);
							const Bytes = plus.android.invoke(ByteArrayOutputStream, 'toByteArray');
							const Base64 = plus.android.importClass("android.util.Base64");
							// 此处必须如此 如果使用 newObject 则 Base64.DEFAULT 为null 如果不 new 直接使用Base64则为null
							const newBase64 = new Base64();
							const Base64Icon = plus.android.invoke(newBase64, "encodeToString", Bytes, Base64.DEFAULT);
							appInfoList.push({
								packName,
								versionName,
								versionCode,
								appName,
								appApkPath,
								appIcon: Base64Icon,
							})

							plus.android.invoke(ByteArrayOutputStream, "close")
						}
						plus.android.invoke(appIcon, "recycle");
						plus.android.invoke(appIconBitmap, "recycle");
					} catch (e) {
						console.log("e：", e);
					}
				}
				console.log("main：", main);
				plus.android.autoCollection(main);
				console.log('获取Android手机系统所有的应用列表appInfoList', appInfoList)
				// #endif
			},

		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 50rpx 30rpx;
	}

	.testBtn {
		text-align: center;
		font-size: 28rpx;
		padding: 16rpx 0;
		border-radius: 12rpx;
		background: pink;
		width: 100%;
		margin: auto;
		color: #fff;
	}
</style>